const { program } = require("commander");
const { options, prodKey, splitKey } = require("./helpers.config");
const { getType } = require("utils-lib-js");
const { rej, Obj2Arr, first2Lower, countArgs } = require("./helpers.others");
const { othersCommand, buildProject } = require("./helpers.extension");
const { currentPackage } = require("./helpers.current");
const { gitTag } = require("./helpers.tag");
const { git } = require("./helpers.git");
const { version, name, description } = require("../package.json");

// 初始化命令函数
exports.initCmd = async () => {
  const [err] = await git.hasGit();
  if (err) return rej(err);
  programOptions(options, program)
    .name(name)
    .version(version)
    .description(description)
    .parse(process.argv);
  const err1 = checkOptions(program);
  if (err1) return rej(err1);
  const { tag, message, others } = executeCommand(program);
  if (!!others.build) {
    const err4 = await buildProject({ tag });
    if (err4) return rej(err4);
  }
  const err2 = await gitTag({ tag, message });
  if (err2) return rej(err2);
  const err3 = await othersCommand({ tag, message, others });
  if (err3) return rej(err3);
};
// 批量添加命令
function programOptions(config, program) {
  config.forEach((it) => program.option(...Obj2Arr(it)));
  return program;
}
// 校验命令
function checkOptions(program) {
  const opts = program.opts();
  if (countArgs(opts, ["Alpha", "Beta", "Release"]) > 1)
    return "只能选择一个后缀，请修改后再操作";
}
// 执行命令
function executeCommand(program) {
  const opts = program.opts();
  const others = {};
  let message = "";
  let tagVersion = currentPackage.version;
  let mixStr = "";
  Reflect.ownKeys(opts).forEach((key) => {
    const it = opts[key];
    const isTypeIsStr = getType(it) === "string";
    switch (key) {
      case "Production":
        const __prodKey = isTypeIsStr ? it : prodKey;
        tagVersion = `${__prodKey}${tagVersion}`;
        break;
      case "CurVer":
        console.log(currentPackage.version);
        break;
      case "Suffix":
        if (!isTypeIsStr) break;
        if (it.startsWith(splitKey)) {
          mixStr = `${it}`;
        } else {
          mixStr = `${splitKey}${it}`;
        }
        break;
      case "Alpha":
      case "Beta":
      case "Release":
        tagVersion = `${tagVersion}${splitKey}${first2Lower(key)}`;
        break;
      case "Message":
        isTypeIsStr && (message = it);
        break;
      case "Publish":
        others.publish = true;
        break;
      case "Build":
        others.build = true;
        break;
    }
  });
  return { tag: tagVersion + mixStr, message, others };
}
